<!DOCTYPE html>
<html lang="zh-CN" layout:decorate="~{layout}">
<head>
    <title>配置编辑器 - HTTP性能测试工具</title>
</head>
<body>
    <div layout:fragment="content" class="container-fluid">
        <!-- 页面头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-edit"></i> 配置编辑器</h2>
                <p class="text-muted mb-0" th:text="${configId != null ? '编辑配置' : '创建新配置'}">创建新配置</p>
            </div>
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-secondary" onclick="previewConfig()">
                    <i class="fas fa-eye"></i> 预览
                </button>
                <button type="button" class="btn btn-success" onclick="saveConfig()">
                    <i class="fas fa-save"></i> 保存
                </button>
                <button type="button" class="btn btn-primary" onclick="validateAndTest()">
                    <i class="fas fa-play"></i> 保存并测试
                </button>
            </div>
        </div>

        <!-- 验证错误提示 -->
        <div id="validation-errors" class="alert alert-danger d-none">
            <h6><i class="fas fa-exclamation-triangle"></i> 配置验证失败</h6>
            <ul id="error-list" class="mb-0"></ul>
        </div>

        <!-- 配置表单 -->
        <form id="config-form">
            <!-- 基本信息 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> 基本信息</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="testName" class="form-label">测试名称 *</label>
                                <input type="text" class="form-control" id="testName" name="testName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="description" class="form-label">测试描述</label>
                                <input type="text" class="form-control" id="description" name="description">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 压测参数 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cogs"></i> 压测参数</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="concurrentUsers" class="form-label">并发用户数 *</label>
                                <input type="number" class="form-control" id="concurrentUsers" name="concurrentUsers" min="1" value="10" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="testDurationSeconds" class="form-label">测试时长(秒) *</label>
                                <input type="number" class="form-control" id="testDurationSeconds" name="testDurationSeconds" min="1" value="60" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="rampUpSeconds" class="form-label">预热时间(秒)</label>
                                <input type="number" class="form-control" id="rampUpSeconds" name="rampUpSeconds" min="0" value="5">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="requestsPerSecond" class="form-label">QPS限制</label>
                                <input type="number" class="form-control" id="requestsPerSecond" name="requestsPerSecond" min="0" value="0" placeholder="0表示无限制">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="reportFormat" class="form-label">报告格式</label>
                                <select class="form-select" id="reportFormat" name="reportFormat">
                                    <option value="console">控制台输出</option>
                                    <option value="html" selected>HTML报告</option>
                                    <option value="json">JSON格式</option>
                                    <option value="csv">CSV格式</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="outputPath" class="form-label">报告输出路径</label>
                                <input type="text" class="form-control" id="outputPath" name="outputPath" value="./test-results">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 全局请求头 -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-globe"></i> 全局请求头</h5>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="addGlobalHeader()">
                        <i class="fas fa-plus"></i> 添加请求头
                    </button>
                </div>
                <div class="card-body">
                    <div id="global-headers-container">
                        <!-- 动态生成的全局请求头将在这里显示 -->
                    </div>
                </div>
            </div>

            <!-- 测试场景 -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-tasks"></i> 测试场景</h5>
                    <button type="button" class="btn btn-primary" onclick="addScenario()">
                        <i class="fas fa-plus"></i> 添加场景
                    </button>
                </div>
                <div class="card-body">
                    <div id="scenarios-container">
                        <!-- 动态生成的场景将在这里显示 -->
                    </div>
                    <div id="no-scenarios" class="text-center text-muted py-5">
                        <i class="fas fa-plus-circle fa-3x mb-3"></i>
                        <p>暂无测试场景，点击上方按钮添加第一个场景</p>
                    </div>
                </div>
            </div>
        </form>

        <!-- 配置预览模态框 -->
        <div class="modal fade" id="previewModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">配置预览</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <small class="text-muted">JSON格式配置文件预览</small>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="copyConfigToClipboard()">
                                <i class="fas fa-copy"></i> 复制
                            </button>
                        </div>
                        <pre id="config-preview" class="bg-light p-3 rounded" style="max-height: 400px; overflow-y: auto;"></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <th:block layout:fragment="scripts">
        <script>
            let configId = null;
            let scenarioCounter = 0;
            let globalHeaderCounter = 0;

            // 页面加载完成后执行
            $(document).ready(function() {
                // 从URL中获取配置ID
                const pathParts = window.location.pathname.split('/');
                if (pathParts.length > 2 && pathParts[2] !== 'new') {
                    configId = pathParts[2];
                    loadConfig(configId);
                } else {
                    // 新建配置时添加默认场景
                    addScenario();
                }
            });

            function loadConfig(id) {
                $.get(`/api/configs/${id}`)
                    .done(function(config) {
                        loadConfigToForm(config);
                    })
                    .fail(function() {
                        AppUtils.showError('加载配置失败');
                    });
            }

            function loadConfigToForm(config) {
                // 填充基本信息
                $('#testName').val(config.testName || '');
                $('#description').val(config.description || '');
                
                // 填充压测参数
                $('#concurrentUsers').val(config.concurrentUsers || 10);
                $('#testDurationSeconds').val(config.testDurationSeconds || 60);
                $('#rampUpSeconds').val(config.rampUpSeconds || 5);
                $('#requestsPerSecond').val(config.requestsPerSecond || 0);
                $('#reportFormat').val(config.reportFormat || 'html');
                $('#outputPath').val(config.outputPath || './test-results');
                
                // 填充全局请求头
                if (config.globalHeaders) {
                    Object.keys(config.globalHeaders).forEach(key => {
                        addGlobalHeader(key, config.globalHeaders[key]);
                    });
                }
                
                // 填充场景
                if (config.scenarios && config.scenarios.length > 0) {
                    config.scenarios.forEach(scenario => {
                        addScenarioToForm(scenario);
                    });
                    $('#no-scenarios').hide();
                } else {
                    addScenario();
                }
            }

            function addGlobalHeader(key = '', value = '') {
                globalHeaderCounter++;
                const headerId = `global-header-${globalHeaderCounter}`;
                
                const headerHtml = `
                    <div class="row mb-2" id="${headerId}">
                        <div class="col-md-5">
                            <input type="text" class="form-control" placeholder="请求头名称" value="${key}">
                        </div>
                        <div class="col-md-6">
                            <input type="text" class="form-control" placeholder="请求头值" value="${value}">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeGlobalHeader('${headerId}')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
                
                $('#global-headers-container').append(headerHtml);
            }

            function removeGlobalHeader(headerId) {
                $(`#${headerId}`).remove();
            }

            function addScenario(scenarioData = null) {
                scenarioCounter++;
                const scenarioId = `scenario-${scenarioCounter}`;
                
                const scenarioHtml = `
                    <div class="card mb-3" id="${scenarioId}">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-outline-secondary me-2" type="button" 
                                            data-bs-toggle="collapse" data-bs-target="#${scenarioId}-body">
                                        <i class="fas fa-chevron-down"></i>
                                    </button>
                                    <input type="text" class="form-control scenario-name" placeholder="场景名称" 
                                           value="${scenarioData?.name || ''}" style="width: 300px;">
                                </div>
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeScenario('${scenarioId}')">
                                    <i class="fas fa-trash"></i> 删除场景
                                </button>
                            </div>
                        </div>
                        <div class="collapse show" id="${scenarioId}-body">
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <label class="form-label">场景描述</label>
                                        <input type="text" class="form-control scenario-description" 
                                               value="${scenarioData?.description || ''}">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">执行模式</label>
                                        <select class="form-select scenario-execution-mode">
                                            <option value="sequential" ${scenarioData?.executionMode === 'sequential' ? 'selected' : ''}>串行</option>
                                            <option value="parallel" ${scenarioData?.executionMode === 'parallel' ? 'selected' : ''}>并行</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">请求间延迟(ms)</label>
                                        <input type="number" class="form-control scenario-delay" min="0" 
                                               value="${scenarioData?.delayBetweenRequests || 0}">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">重复次数</label>
                                        <input type="number" class="form-control scenario-repeat" min="1" 
                                               value="${scenarioData?.repeatCount || 1}">
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-check mt-4">
                                            <input class="form-check-input scenario-enabled" type="checkbox" 
                                                   ${scenarioData?.enabled !== false ? 'checked' : ''}>
                                            <label class="form-check-label">启用场景</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6><i class="fas fa-globe"></i> HTTP请求</h6>
                                    <button type="button" class="btn btn-sm btn-primary" onclick="addRequest('${scenarioId}')">
                                        <i class="fas fa-plus"></i> 添加请求
                                    </button>
                                </div>
                                
                                <div class="requests-container" id="${scenarioId}-requests">
                                    <!-- 请求列表将在这里显示 -->
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                $('#scenarios-container').append(scenarioHtml);
                $('#no-scenarios').hide();
                
                // 如果有场景数据，添加其中的请求
                if (scenarioData && scenarioData.requests) {
                    scenarioData.requests.forEach(request => {
                        addRequest(scenarioId, request);
                    });
                } else {
                    // 默认添加一个空请求
                    addRequest(scenarioId);
                }
            }

            function addScenarioToForm(scenarioData) {
                addScenario(scenarioData);
            }

            function removeScenario(scenarioId) {
                $(`#${scenarioId}`).remove();
                
                // 检查是否还有场景，没有则显示提示
                if ($('#scenarios-container .card').length === 0) {
                    $('#no-scenarios').show();
                }
            }

            function addRequest(scenarioId, requestData = null) {
                const requestId = `${scenarioId}-request-${Date.now()}`;
                
                const requestHtml = `
                    <div class="border rounded mb-3 p-3" id="${requestId}">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0"><i class="fas fa-link"></i> HTTP请求</h6>
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeRequest('${requestId}')">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">请求名称 *</label>
                                <input type="text" class="form-control request-name" 
                                       value="${requestData?.name || ''}" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">请求描述</label>
                                <input type="text" class="form-control request-description" 
                                       value="${requestData?.description || ''}">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-2">
                                <label class="form-label">HTTP方法 *</label>
                                <select class="form-select request-method" required>
                                    <option value="GET" ${requestData?.method === 'GET' ? 'selected' : ''}>GET</option>
                                    <option value="POST" ${requestData?.method === 'POST' ? 'selected' : ''}>POST</option>
                                    <option value="PUT" ${requestData?.method === 'PUT' ? 'selected' : ''}>PUT</option>
                                    <option value="DELETE" ${requestData?.method === 'DELETE' ? 'selected' : ''}>DELETE</option>
                                    <option value="PATCH" ${requestData?.method === 'PATCH' ? 'selected' : ''}>PATCH</option>
                                    <option value="HEAD" ${requestData?.method === 'HEAD' ? 'selected' : ''}>HEAD</option>
                                    <option value="OPTIONS" ${requestData?.method === 'OPTIONS' ? 'selected' : ''}>OPTIONS</option>
                                </select>
                            </div>
                            <div class="col-md-7">
                                <label class="form-label">请求URL *</label>
                                <input type="url" class="form-control request-url" 
                                       value="${requestData?.url || ''}" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">超时时间(ms)</label>
                                <input type="number" class="form-control request-timeout" min="1" 
                                       value="${requestData?.timeout || 30000}">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">期望状态码</label>
                                <input type="number" class="form-control request-status-code" min="100" max="599" 
                                       value="${requestData?.expectedStatusCode || 200}">
                            </div>
                        </div>
                        
                        <!-- 请求头 -->
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <label class="form-label mb-0">请求头</label>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addRequestHeader('${requestId}')">
                                    <i class="fas fa-plus"></i> 添加
                                </button>
                            </div>
                            <div class="request-headers-container" id="${requestId}-headers">
                                <!-- 请求头将在这里显示 -->
                            </div>
                        </div>
                        
                        <!-- 请求体 -->
                        <div class="mb-3">
                            <label class="form-label">请求体 (JSON/XML/Text)</label>
                            <textarea class="form-control request-body" rows="4" 
                                      placeholder="请求体内容...">${requestData?.body || ''}</textarea>
                        </div>
                    </div>
                `;
                
                $(`#${scenarioId}-requests`).append(requestHtml);
                
                // 如果有请求头数据，添加请求头
                if (requestData && requestData.headers) {
                    Object.keys(requestData.headers).forEach(key => {
                        addRequestHeader(requestId, key, requestData.headers[key]);
                    });
                }
            }

            function removeRequest(requestId) {
                $(`#${requestId}`).remove();
            }

            function addRequestHeader(requestId, key = '', value = '') {
                const headerId = `${requestId}-header-${Date.now()}`;
                
                const headerHtml = `
                    <div class="row mb-2" id="${headerId}">
                        <div class="col-md-5">
                            <input type="text" class="form-control" placeholder="请求头名称" value="${key}">
                        </div>
                        <div class="col-md-6">
                            <input type="text" class="form-control" placeholder="请求头值" value="${value}">
                        </div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeRequestHeader('${headerId}')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
                
                $(`#${requestId}-headers`).append(headerHtml);
            }

            function removeRequestHeader(headerId) {
                $(`#${headerId}`).remove();
            }

            function collectFormData() {
                const config = {
                    testName: $('#testName').val(),
                    description: $('#description').val(),
                    concurrentUsers: parseInt($('#concurrentUsers').val()) || 10,
                    testDurationSeconds: parseInt($('#testDurationSeconds').val()) || 60,
                    rampUpSeconds: parseInt($('#rampUpSeconds').val()) || 5,
                    requestsPerSecond: parseInt($('#requestsPerSecond').val()) || 0,
                    reportFormat: $('#reportFormat').val() || 'html',
                    outputPath: $('#outputPath').val() || './test-results',
                    globalHeaders: {},
                    scenarios: []
                };
                
                // 收集全局请求头
                $('#global-headers-container .row').each(function() {
                    const key = $(this).find('input').eq(0).val().trim();
                    const value = $(this).find('input').eq(1).val().trim();
                    if (key && value) {
                        config.globalHeaders[key] = value;
                    }
                });
                
                // 收集场景
                $('#scenarios-container .card').each(function() {
                    const $scenario = $(this);
                    const scenario = {
                        name: $scenario.find('.scenario-name').val() || '',
                        description: $scenario.find('.scenario-description').val() || '',
                        executionMode: $scenario.find('.scenario-execution-mode').val() || 'sequential',
                        delayBetweenRequests: parseInt($scenario.find('.scenario-delay').val()) || 0,
                        repeatCount: parseInt($scenario.find('.scenario-repeat').val()) || 1,
                        enabled: $scenario.find('.scenario-enabled').is(':checked'),
                        requests: []
                    };
                    
                    // 收集场景中的请求
                    $scenario.find('.requests-container > div').each(function() {
                        const $request = $(this);
                        const request = {
                            name: $request.find('.request-name').val() || '',
                            description: $request.find('.request-description').val() || '',
                            method: $request.find('.request-method').val() || 'GET',
                            url: $request.find('.request-url').val() || '',
                            timeout: parseInt($request.find('.request-timeout').val()) || 30000,
                            expectedStatusCode: parseInt($request.find('.request-status-code').val()) || 200,
                            body: $request.find('.request-body').val() || '',
                            headers: {}
                        };
                        
                        // 收集请求头
                        $request.find('.request-headers-container .row').each(function() {
                            const key = $(this).find('input').eq(0).val().trim();
                            const value = $(this).find('input').eq(1).val().trim();
                            if (key && value) {
                                request.headers[key] = value;
                            }
                        });
                        
                        scenario.requests.push(request);
                    });
                    
                    config.scenarios.push(scenario);
                });
                
                return config;
            }
            
            function validateConfig() {
                const config = collectFormData();
                
                $.ajax({
                    url: '/api/configs/validate',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(config)
                })
                .done(function(result) {
                    if (result.valid) {
                        $('#validation-errors').hide();
                        AppUtils.showSuccess('配置验证成功');
                    } else {
                        showValidationErrors(result.errors);
                    }
                })
                .fail(function() {
                    AppUtils.showError('配置验证失败');
                });
            }
            
            function showValidationErrors(errors) {
                const errorList = $('#error-list');
                errorList.empty();
                
                errors.forEach(error => {
                    errorList.append(`<li>${escapeHtml(error)}</li>`);
                });
                
                $('#validation-errors').show();
            }
            
            function saveConfig() {
                const config = collectFormData();
                const url = configId ? `/api/configs/${configId}` : '/api/configs';
                const method = configId ? 'PUT' : 'POST';
                
                $.ajax({
                    url: url,
                    method: method,
                    contentType: 'application/json',
                    data: JSON.stringify(config)
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('配置保存成功');
                        if (response.configId) {
                            configId = response.configId;
                            window.history.replaceState({}, '', `/configs/${configId}/edit`);
                        }
                        $('#validation-errors').hide();
                    } else {
                        if (response.errors) {
                            showValidationErrors(response.errors);
                        }
                        AppUtils.showError(response.message || '配置保存失败');
                    }
                })
                .fail(function() {
                    AppUtils.showError('配置保存失败');
                });
            }
            
            function validateAndTest() {
                const config = collectFormData();
                
                $.ajax({
                    url: '/api/configs/validate',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(config)
                })
                .done(function(result) {
                    if (result.valid) {
                        saveConfig();
                        setTimeout(() => {
                            startTestWithConfig(config);
                        }, 1000);
                    } else {
                        showValidationErrors(result.errors);
                        AppUtils.showError('配置验证失败，无法启动测试');
                    }
                });
            }
            
            function startTestWithConfig(config) {
                if (!configId) {
                    AppUtils.showError('请先保存配置');
                    return;
                }
                
                $.ajax({
                    url: '/api/tests/start',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ configId: configId })
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('测试启动成功');
                        window.location.href = `/tests/${response.sessionId}/monitor`;
                    } else {
                        AppUtils.showError(response.message || '测试启动失败');
                    }
                });
            }
            
            function previewConfig() {
                const config = collectFormData();
                const yaml = JSON.stringify(config, null, 2);
                $('#config-preview').text(yaml);
                new bootstrap.Modal(document.getElementById('previewModal')).show();
            }
            
            function copyConfigToClipboard() {
                const content = $('#config-preview').text();
                navigator.clipboard.writeText(content).then(() => {
                    AppUtils.showSuccess('配置已复制到剪贴板');
                });
            }
            
            function escapeHtml(text) {
                if (!text) return '';
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        </script>
    </th:block>
</html>